// 公共组件

// 底部导航栏
function renderBottomNav(activePage = 'home') {
    return `
    <nav class="fixed bottom-0 left-0 right-0 max-w-md mx-auto bg-white border-t border-gray-200 z-20 shadow-xl">
        <div class="flex justify-around items-center h-16 px-2">
            <a href="../index.html" class="nav-item flex flex-col items-center justify-center flex-1 py-2 ${activePage === 'home' ? 'text-primary' : 'text-text-secondary'} relative">
                <i class="fa fa-home text-xl mb-1"></i>
                <span class="text-xs ${activePage === 'home' ? 'font-medium' : ''}">首页</span>
                ${activePage === 'home' ? '<span class="absolute bottom-0 w-8 h-0.5 bg-primary rounded-full"></span>' : ''}
            </a>
            
            <a href="../pages/service.html" class="nav-item flex flex-col items-center justify-center flex-1 py-2 ${activePage === 'service' ? 'text-primary' : 'text-text-secondary'} relative">
                <i class="fa fa-handshake text-xl mb-1"></i>
                <span class="text-xs ${activePage === 'service' ? 'font-medium' : ''}">服务</span>
                ${activePage === 'service' ? '<span class="absolute bottom-0 w-8 h-0.5 bg-primary rounded-full"></span>' : ''}
            </a>
            
            <button class="publish-btn w-14 h-14 gradient-primary rounded-2xl -mt-7 flex items-center justify-center shadow-large relative overflow-hidden group" onclick="showPublishModal()">
                <i class="fa fa-plus text-white text-2xl relative z-10 group-hover:rotate-90 transition-transform duration-300"></i>
                <div class="absolute inset-0 bg-white/20 opacity-0 group-hover:opacity-100 transition-opacity"></div>
            </button>
            
            <a href="../pages/demand.html" class="nav-item flex flex-col items-center justify-center flex-1 py-2 ${activePage === 'demand' ? 'text-primary' : 'text-text-secondary'} relative">
                <i class="fa fa-list-alt text-xl mb-1"></i>
                <span class="text-xs ${activePage === 'demand' ? 'font-medium' : ''}">需求</span>
                ${activePage === 'demand' ? '<span class="absolute bottom-0 w-8 h-0.5 bg-primary rounded-full"></span>' : ''}
            </a>
            
            <a href="../pages/my.html" class="nav-item flex flex-col items-center justify-center flex-1 py-2 ${activePage === 'my' ? 'text-primary' : 'text-text-secondary'} relative">
                <i class="fa fa-user text-xl mb-1"></i>
                <span class="text-xs ${activePage === 'my' ? 'font-medium' : ''}">我的</span>
                ${activePage === 'my' ? '<span class="absolute bottom-0 w-8 h-0.5 bg-primary rounded-full"></span>' : ''}
            </a>
        </div>
    </nav>
    `;
}

// 发布弹框
function renderPublishModal() {
    return `
    <div id="publish-modal" class="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 hidden items-end" style="display: none;">
        <div class="bg-white rounded-t-3xl w-full p-6 shadow-xl">
            <div class="flex items-center justify-between mb-5">
                <h3 class="text-lg font-bold text-text-primary">选择发布类型</h3>
                <button onclick="closePublishModal()" class="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center hover:bg-gray-200 transition-colors">
                    <i class="fa fa-times text-gray-600"></i>
                </button>
            </div>
            
            <div class="grid grid-cols-2 gap-4 mb-6">
                <button class="group card-modern p-5 text-left hover:border-primary/50" onclick="navigateToDemandPublish()">
                    <div class="w-12 h-12 rounded-2xl gradient-secondary flex items-center justify-center mb-3 group-hover:scale-110 transition-transform">
                        <i class="fa fa-list-alt text-white text-xl"></i>
                    </div>
                    <h4 class="text-sm font-bold text-text-primary mb-1">发布需求</h4>
                    <p class="text-xs text-text-secondary">快速匹配服务商</p>
                </button>
                
                <button class="group card-modern p-5 text-left hover:border-primary/50" onclick="navigateToServicePublish()">
                    <div class="w-12 h-12 rounded-2xl gradient-primary flex items-center justify-center mb-3 group-hover:scale-110 transition-transform">
                        <i class="fa fa-handshake text-white text-xl"></i>
                    </div>
                    <h4 class="text-sm font-bold text-text-primary mb-1">发布服务</h4>
                    <p class="text-xs text-text-secondary">展示服务能力</p>
                </button>
            </div>
        </div>
    </div>
    `;
}

// 显示发布弹框
function showPublishModal() {
    const modal = document.getElementById('publish-modal');
    if (modal) {
        modal.classList.remove('hidden');
        modal.style.display = 'flex';
    }
}

// 关闭发布弹框
function closePublishModal() {
    const modal = document.getElementById('publish-modal');
    if (modal) {
        modal.style.opacity = '0';
        setTimeout(() => {
            modal.classList.add('hidden');
            modal.style.display = 'none';
            modal.style.opacity = '1';
        }, 300);
    }
}

// 点击弹框外部关闭
function initModalClose() {
    const modal = document.getElementById('publish-modal');
    if (modal) {
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                closePublishModal();
            }
        });
    }
}

// 导航到发布需求页面
function navigateToDemandPublish() {
    closePublishModal();
    // 检查登录状态
    if (CommonUtils.checkLoginRequired(() => {}, '发布需求')) {
        // 根据当前页面判断路径
        const currentPath = window.location.pathname;
        if (currentPath.includes('/pages/')) {
            window.location.href = './publish-demand.html';
        } else {
            window.location.href = './pages/publish-demand.html';
        }
    }
}

// 导航到发布服务页面
function navigateToServicePublish() {
    closePublishModal();
    // 检查登录状态
    if (CommonUtils.checkLoginRequired(() => {}, '发布服务')) {
        // 根据当前页面判断路径
        const currentPath = window.location.pathname;
        if (currentPath.includes('/pages/')) {
            window.location.href = './publish-service.html';
        } else {
            window.location.href = './pages/publish-service.html';
        }
    }
}

// 初始化组件
function initComponents(activePage) {
    // 渲染底部导航
    const navContainer = document.getElementById('bottom-nav');
    if (navContainer) {
        navContainer.innerHTML = renderBottomNav(activePage);
    }
    
    // 渲染发布弹框
    const modalContainer = document.getElementById('publish-modal-container');
    if (modalContainer) {
        modalContainer.innerHTML = renderPublishModal();
    }
    
    // 初始化弹框关闭事件
    initModalClose();
}

// 联系表单弹框
function renderContactModal() {
    return `
    <div id="contact-modal" class="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 hidden items-center justify-center p-4" style="display: none;">
        <div class="bg-white rounded-3xl w-full max-w-md max-h-[90vh] overflow-y-auto shadow-xl">
            <div class="sticky top-0 bg-white border-b border-gray-100 px-6 py-4 rounded-t-3xl">
                <div class="flex items-center justify-between">
                    <h3 class="text-lg font-bold text-text-primary">联系对方</h3>
                    <button onclick="Components.closeContactModal()" class="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center hover:bg-gray-200 transition-colors">
                        <i class="fa fa-times text-gray-600"></i>
                    </button>
                </div>
            </div>
            
            <form id="contact-form" class="p-6 space-y-4">
                <!-- 联系对象信息 -->
                <div class="bg-gradient-to-br from-primary/5 to-secondary/5 rounded-2xl p-4 border border-primary/20">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
                            <i class="fa fa-user text-primary text-lg"></i>
                        </div>
                        <div>
                            <p class="text-sm font-bold text-text-primary" id="contact-target-name">联系人</p>
                            <p class="text-xs text-text-secondary" id="contact-target-phone">联系电话</p>
                        </div>
                    </div>
                </div>
                
                <!-- 联系内容 -->
                <div>
                    <label class="block text-sm font-medium text-text-primary mb-2">
                        <i class="fa fa-comment mr-1 text-primary"></i>联系内容 <span class="text-danger">*</span>
                    </label>
                    <textarea id="contact-content" 
                        class="w-full px-4 py-3 bg-neutral border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all resize-none" 
                        rows="4" 
                        placeholder="请输入您想说的话..."
                        required></textarea>
                </div>
                
                <!-- 附件上传 -->
                <div>
                    <label class="block text-sm font-medium text-text-primary mb-2">
                        <i class="fa fa-paperclip mr-1 text-primary"></i>附件（可选）
                    </label>
                    <div class="relative">
                        <input type="file" id="contact-attachment" 
                            class="hidden" 
                            accept="image/*,.pdf,.doc,.docx"
                            onchange="Components.handleFileSelect(event)">
                        <button type="button" 
                            onclick="document.getElementById('contact-attachment').click()" 
                            class="w-full px-4 py-3 bg-neutral border border-gray-200 rounded-xl text-sm text-left text-text-secondary hover:border-primary transition-all flex items-center gap-2">
                            <i class="fa fa-cloud-upload text-primary"></i>
                            <span id="file-name">点击选择文件</span>
                        </button>
                    </div>
                </div>
                
                <!-- 我的联系信息 -->
                <div class="border-t border-gray-100 pt-4">
                    <p class="text-sm font-medium text-text-primary mb-3">
                        <i class="fa fa-user-circle-o mr-1 text-primary"></i>我的联系信息
                    </p>
                    <div class="space-y-3">
                        <div>
                            <label class="block text-xs text-text-secondary mb-1.5">联系人 <span class="text-danger">*</span></label>
                            <input type="text" id="contact-my-name" 
                                class="w-full px-4 py-2.5 bg-neutral border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all" 
                                placeholder="请输入您的姓名"
                                required>
                        </div>
                        <div>
                            <label class="block text-xs text-text-secondary mb-1.5">联系电话 <span class="text-danger">*</span></label>
                            <input type="tel" id="contact-my-phone" 
                                class="w-full px-4 py-2.5 bg-neutral border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all" 
                                placeholder="请输入您的手机号码"
                                pattern="^1[3-9]\\d{9}$"
                                required>
                        </div>
                    </div>
                </div>
                
                <!-- 提交按钮 -->
                <div class="flex gap-3 pt-2">
                    <button type="button" 
                        onclick="Components.closeContactModal()" 
                        class="flex-1 px-6 py-3 bg-gray-100 text-text-primary rounded-xl text-sm font-medium hover:bg-gray-200 transition-colors">
                        取消
                    </button>
                    <button type="submit" 
                        class="flex-1 px-6 py-3 gradient-primary text-white rounded-xl text-sm font-medium hover:opacity-90 transition-opacity">
                        发送
                    </button>
                </div>
            </form>
        </div>
    </div>
    `;
}

// 显示联系弹框
function showContactModal(targetName, targetPhone) {
    // 如果弹框不存在，先创建
    if (!document.getElementById('contact-modal')) {
        const modalContainer = document.createElement('div');
        modalContainer.innerHTML = renderContactModal();
        document.body.appendChild(modalContainer.firstElementChild);
    }
    
    const modal = document.getElementById('contact-modal');
    if (modal) {
        // 设置联系对象信息
        document.getElementById('contact-target-name').textContent = targetName || '联系人';
        document.getElementById('contact-target-phone').textContent = targetPhone || '联系电话';
        
        // 填充当前登录人信息（模拟数据，实际应从登录状态获取）
        const currentUser = getCurrentUser();
        document.getElementById('contact-my-name').value = currentUser.name || '';
        document.getElementById('contact-my-phone').value = currentUser.phone || '';
        
        // 重置表单
        document.getElementById('contact-content').value = '';
        document.getElementById('contact-attachment').value = '';
        document.getElementById('file-name').textContent = '点击选择文件';
        
        // 显示弹框
        modal.classList.remove('hidden');
        modal.style.display = 'flex';
        
        // 绑定表单提交事件
        const form = document.getElementById('contact-form');
        form.onsubmit = handleContactSubmit;
    }
}

// 关闭联系弹框
function closeContactModal() {
    const modal = document.getElementById('contact-modal');
    if (modal) {
        modal.style.opacity = '0';
        setTimeout(() => {
            modal.classList.add('hidden');
            modal.style.display = 'none';
            modal.style.opacity = '1';
        }, 300);
    }
}

// 处理文件选择
function handleFileSelect(event) {
    const file = event.target.files[0];
    const fileNameSpan = document.getElementById('file-name');
    if (file) {
        fileNameSpan.textContent = file.name;
        fileNameSpan.classList.add('text-primary', 'font-medium');
    } else {
        fileNameSpan.textContent = '点击选择文件';
        fileNameSpan.classList.remove('text-primary', 'font-medium');
    }
}

// 获取当前登录用户信息（模拟函数，预留接口）
function getCurrentUser() {
    // TODO: 实际项目中应从登录状态或localStorage中获取
    // 这里返回模拟数据
    const mockUser = {
        name: '张三',
        phone: '138****5678'
    };
    
    // 尝试从localStorage获取
    const storedUser = localStorage.getItem('currentUser');
    if (storedUser) {
        try {
            return JSON.parse(storedUser);
        } catch (e) {
            console.warn('解析用户信息失败', e);
        }
    }
    
    return mockUser;
}

// 处理联系表单提交
function handleContactSubmit(event) {
    event.preventDefault();
    
    // 获取表单数据
    const formData = {
        targetName: document.getElementById('contact-target-name').textContent,
        targetPhone: document.getElementById('contact-target-phone').textContent,
        content: document.getElementById('contact-content').value,
        attachment: document.getElementById('contact-attachment').files[0],
        myName: document.getElementById('contact-my-name').value,
        myPhone: document.getElementById('contact-my-phone').value
    };
    
    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(formData.myPhone)) {
        CommonUtils.showToast('请输入正确的手机号码', 'warning');
        return;
    }
    
    // TODO: 预留接口 - 调用后端API提交联系信息
    console.log('提交联系信息:', formData);
    submitContactRequest(formData);
}

// 提交联系请求（预留接口）
async function submitContactRequest(formData) {
    try {
        // TODO: 实际项目中应调用后端API
        // const response = await fetch('/api/contact/submit', {
        //     method: 'POST',
        //     headers: {
        //         'Content-Type': 'application/json',
        //     },
        //     body: JSON.stringify(formData)
        // });
        // const result = await response.json();
        
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        CommonUtils.showToast('发送成功！对方会尽快与您联系', 'success');
        closeContactModal();
        
        // 保存用户信息到localStorage
        localStorage.setItem('currentUser', JSON.stringify({
            name: formData.myName,
            phone: formData.myPhone
        }));
        
    } catch (error) {
        console.error('提交失败:', error);
        CommonUtils.showToast('发送失败，请稍后重试', 'error');
    }
}

// 点击弹框外部关闭
document.addEventListener('click', function(e) {
    const contactModal = document.getElementById('contact-modal');
    if (contactModal && e.target === contactModal) {
        closeContactModal();
    }
});

// 导出函数
window.Components = {
    renderBottomNav,
    renderPublishModal,
    showPublishModal,
    closePublishModal,
    initComponents,
    renderContactModal,
    showContactModal,
    closeContactModal,
    handleFileSelect,
    getCurrentUser
};

